package com.imooc.miaosha.validator;

import com.imooc.miaosha.util.ValidatorUtils;
import com.imooc.miaosha.validator.annotation.IsMobile;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 模块描述: <br>
 * ()
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/17 1:06
 * @since: 1.8.0
 * @version: 1.0.0
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            return ValidatorUtils.isMobile(s);
        } else {
            if (StringUtils.isEmpty(s)) {
                return true;
            }
            return ValidatorUtils.isMobile(s);
        }
    }
}
